
//
//  MyCreationViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/25.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Networking
import Alamofire
import PKHUD
import SwiftyJSON

enum MineContentType: NSInteger {
    case comment = 0
    case zan
    case system
}
class MyCreationViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource,AddCornerUIRectCorner, BottomShadow,ConsultaionTableViewCellDelegate  {
   @IBOutlet weak var cornerSelectionView: CornerSelectionView!
    
    @IBOutlet weak var mainTableView: UITableView!
    
    var mineContentType: MineContentType = .comment
    
    var data1:[MyContentModel] = []
    // 顶部刷新mainTableView
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    var page:Int = 1
    var totalPage:Int = 0
    var indexPath :IndexPath?
    let notiName:String = "MYCreationReloadCell"

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(notificationAction), name:NSNotification.Name(rawValue: notiName), object: nil)
        setUI()
    }
    
    @objc private func notificationAction(noti: Notification) {
        if self.mineContentType == .comment || self.mineContentType == .system {
            if indexPath != nil {
                var model:MyContentModel = self.data1[(self.indexPath?.row)!]
                if noti.object is ArticleModel {
                    let ar:ArticleModel = noti.object as! ArticleModel
                    model.collected = ar.collected
                    model.favorite = ar.favorite
                    model.comment = ar.comment
                    model.browse = ar.browse
                }else {
                    let ar:VideoModel = noti.object as! VideoModel
                    model.collected = ar.collected
                    model.favorite = ar.favorite
                    model.comment = ar.comment
                    model.browse = ar.browse
                }
                self.data1[(self.indexPath?.row)!] = model
                self.mainTableView.reloadRows(at: [self.indexPath!], with: UITableViewRowAnimation.automatic)
            }
        }
    }
    
    func setUI() {
        titleLabel(text: "我的内容", nil)
        mainTableView.estimatedRowHeight = 100;
        mainTableView.rowHeight = UITableViewAutomaticDimension;
        mainTableView.register(UINib(nibName: "\(ConsultaionTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
        cornerSelectionView.show(titles: ["已发布", "草稿箱", "收藏"]) {[unowned self] (index) in
            let corner: UIRectCorner!
            self.data1.removeAll()
            self.page = 1
            switch index {
            case 0:
                corner = .topRight
                self.fetchMyContent(parameters: ["page":self.page,"pageSize":10],uri:myContentUrl)
            case 2:
                corner = .topLeft
                self.fetchMyContent(parameters: ["page":self.page,"pageSize":10,"objType":0],uri:myShoucangUrl)
            default:
                corner = [.topRight, .topLeft]
                self.fetchMyContent(parameters: ["page":self.page,"pageSize":10],uri:myContentCGUrl)
            }

            self.mineContentType = MineContentType(rawValue: index)!
            self.mainTableView.reloadData()
        }
        let headerAction:Selector = #selector(headerRefresh)
        header.setRefreshingTarget(self, refreshingAction: headerAction)
        mainTableView.mj_header = header
        mainTableView.mj_footer = footer
        let footerAction:Selector = #selector(footerRefresh)
        footer.setRefreshingTarget(self, refreshingAction: footerAction)
        self.headerRefresh()
    }
    
    // 顶部刷新
    @objc func headerRefresh(){
        print("下拉刷新") // 结束刷新
        page = 0
        self.footerRefresh()

    }
    // 底部刷新
    @objc func footerRefresh(){
        print("上拉刷新")
        page += 1
        switch self.mineContentType {
        case .comment:
            self.fetchMyContent(parameters: ["page":page,"pageSize":10],uri:myContentUrl)
        case .zan:
            self.fetchMyContent(parameters: ["page":page,"pageSize":10],uri:myContentCGUrl)
        case .system:
            self.fetchMyContent(parameters: ["page":page,"pageSize":10,"objType":0],uri:myShoucangUrl)
        }
    }
    
    override func setNavigation() {
    }
    
    
    // MARK: tableViewDatasource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let model = self.data1
        return model.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? ConsultaionTableViewCell
        let model = self.data1[indexPath.row]
        var isDel:Bool = false
        var isShow:Bool = false
        switch self.mineContentType {
        case .comment:
            isDel = true
            isShow = true
        case .zan:
            isDel = true
        case .system:
            isDel = false
        }
        cell?.showContent1(model: model, flag: isDel ,showStatus: isShow)
        cell?.delegate = self
        cell?.deleteblock = {
            self.data1.remove(at: indexPath.row)
            self.mainTableView.reloadData()
        }
        return cell!
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.indexPath = indexPath
        let model = self.data1[indexPath.row]
        switch self.mineContentType {
            case .comment:
                self.gotoView(model: model)
            case .zan:
                if model.redirectType == "1"{
                   
                    let richTextEditViewController = PublishViewController(nibName: "PublishViewController", bundle: nil)
                    let mainNavigation = MainNavigaionViewController(rootViewController: richTextEditViewController)
                    richTextEditViewController.contentId = model.id
                    self.present(mainNavigation, animated: true, completion: nil)
                }else{
                    let richTextEditViewController = PublishViewController(nibName: "PublishViewController", bundle: nil)
                    richTextEditViewController.isVideo = true
                    let mainNavigation = MainNavigaionViewController(rootViewController: richTextEditViewController)
                    richTextEditViewController.contentId = model.id
                    self.present(mainNavigation, animated: true, completion: nil)
                  
                }
                
                
                return
            case .system:
                self.gotoView(model: model)
        }
    }
    
    func gotoView(model : MyContentModel) {
        if model.redirectType == "1" {
            let consultationDetailVC = ConsultationDetailViewController(nibName: "\(ConsultationDetailViewController.self)", bundle: nil, type: .news)
            consultationDetailVC.title = model.title
            var mo : ArticleModel = ArticleModel()
            mo.id = model.id
            mo.title = model.title
            mo.coverImgPath = model.image
            consultationDetailVC.model = mo
            consultationDetailVC.showRightButtonType = .all
            consultationDetailVC.notiName = self.notiName
            navigationController?.pushViewController(consultationDetailVC, animated: true)
        }else {
            let consultationDetailVC = VideoDetailViewController(nibName: "\(VideoDetailViewController.self)", bundle: nil, type: .video)
            consultationDetailVC.title = model.title
            var mo : VideoModel = VideoModel()
            mo.id = model.id
            mo.title = model.title
            mo.coverImgPath = model.image
            consultationDetailVC.model = mo
            consultationDetailVC.showRightButtonType = .all
            consultationDetailVC.notiName = self.notiName
            navigationController?.pushViewController(consultationDetailVC, animated: true)
        }
    }
    
    /// 获取我的内容
    func fetchMyContent(parameters: [String: Any], uri : String) -> Void {
        let requesturl = "\(BaseURL)\(uri)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){

                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let data = json["data"].dictionary!
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = data["rows"]?.array!
                                        if self.page == 1{
                                            self.data1.removeAll()
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        for subject in arr! {
                                            let dic = subject.dictionary!
                                            var model = MyContentModel(fromDic: dic)

                                            let author = dic["author"]
                                            if !(author?.isEmpty)!{
                                                model.initAuthor(dic: (author?.dictionary!)!)
                                            }
                                            let grade = dic["author"]!["grade"]
                                            if !grade.isEmpty{
                                                model.author?.initGrade(dic: (grade.dictionary!))
                                            }
                                            self.data1.append(model)

                                        }
                                        if self.totalPage == self.data1.count{
                                            self.mainTableView.mj_footer=nil
                                        }
                                        else{
                                            self.mainTableView.mj_footer = self.footer
                                        }
                                        self.mainTableView.reloadData()

                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        if self.page == 1{
                                            self.mainTableView.mj_header.endRefreshing()
                                        }
                                        else{
                                            self.mainTableView.mj_footer.endRefreshing()
                                        }
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                if self.page == 1{
                                    self.data1.removeAll()
                                    self.mainTableView.mj_header.endRefreshing()
                                }
                                else{
                                    self.mainTableView.mj_footer.endRefreshing()
                                }
                                print("请求失败\(String(describing: response.error))")
                            }

        }

    }
    
    func delCell(model:MyContentModel, cell: ConsultaionTableViewCell) -> Void {
        let alertController = UIAlertController(title: "删除内容？", message: nil, preferredStyle: .alert)
        
        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: { (_) in
            
        })
        let sureAction = UIAlertAction.init(title: "确定", style: .default, handler: { (_) in
            var url = appendUrl(suffix: deleteArticleUrl)
            if model.redirectType != "1"{
                url = appendUrl(suffix: deleteVideoUrl)
            }
            let aid:String = (model.id)!;
            let parameter:[String : String] = ["id": aid]
            Alamofire.request(url, method: .post,
                              parameters: parameter,
                              encoding: URLEncoding.default,
                              headers: ["token":MineInfoModel.share.token!]).responseJSON {
                                (response) in
                                
                                if(response.error == nil){
                                    if let result = response.result.value as? NSDictionary
                                    {
                                        
                                        let json = JSON(result)
                                        if json["code"].int == 1{
                                            self.showToast(msg:json["message"].stringValue)
                                            cell.deleteblock!()
                                        }else if json["code"].int == 100{
                                            self.showToast(msg:json["message"].string!)
                                            let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                            self.navigationController?.pushViewController(loginVC, animated: true)
                                        }
                                        else{
                                            self.showToast(msg:json["message"].string!)
                                        }
                                    }
                                }else{
                                    self.showToast(msg:"删除失败")
                                }
                                
            }
        })
        alertController.addAction(cancel)
        alertController.addAction(sureAction)
        self.present(alertController, animated: true, completion: nil)
    }
}
